part of '../repository.dart';

const _kCollectionFolderIdKey = 'id';
const _kCollectionFolderTitlesKey = 'titles';
const _kCollectionFolderCollectionsKey = 'collections';

const _kCollectionListItemCollectionFolderType = 'inbuilt_collection_folder';

class _CollectionFolderDto extends Equatable implements _CollectionListItemDto {
  const _CollectionFolderDto._internal({
    required this.id,
    required this.titles,
    required this.collectionDtos,
  });

  final String id;
  final BuiltMap<String, String> titles;
  final BuiltList<_CollectionDto> collectionDtos;

  @override
  String get type => _kCollectionListItemCollectionFolderType;

  @override
  List<Object?> get props {
    return [
      id,
      titles,
      collectionDtos,
    ];
  }

  factory _CollectionFolderDto.fromJson(Map<String, dynamic> json) {
    final titleMap = json[_kCollectionFolderTitlesKey] as Map;

    final titles = titleMap.map((languageCode, title) {
      return MapEntry(languageCode as String, title as String);
    }).build();

    final collectionMaps = List.castFrom<dynamic, Map>(json[_kCollectionFolderCollectionsKey]);

    final collectionDtos = collectionMaps.map((collectionMap) {
      final collectionJson = Map.castFrom<dynamic, dynamic, String, dynamic>(collectionMap);
      return _CollectionDto.fromJson(collectionJson);
    }).toBuiltList();

    return _CollectionFolderDto._internal(
      id: json[_kCollectionFolderIdKey],
      titles: titles,
      collectionDtos: collectionDtos,
    );
  }

  @override
  AssetCollectionFolder toEntity() {
    final collections = collectionDtos.map((collectionDto) {
      return collectionDto.toEntity();
    }).toBuiltList();

    return AssetCollectionFolder(
      id: id,
      titles: titles,
      collections: collections,
    );
  }
}
